package com.mymarkdown.app.fx.event.hander.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.mymarkdown.app.common.lister.FileWatch;
import com.mymarkdown.app.fx.annotation.KeyWord;
import com.mymarkdown.app.fx.assemblys.FxTreeItem;
import com.mymarkdown.app.fx.enums.FxEventEnum;
import com.mymarkdown.app.fx.event.hander.KeyWordHandler;
import com.mymarkdown.app.fx.event.hander.MenuHandler;
import com.mymarkdown.app.fx.event.model.FxEvent;
import com.mymarkdown.app.interfaces.ModifyWindow;
import com.mymarkdown.app.interfaces.UserInfoService;
import com.mymarkdown.app.util.CurrentUserUtil;
import com.mymarkdown.app.websocket.enums.MessageTypeEnum;
import com.mymarkdown.app.fx.FxApplication;
import com.mymarkdown.app.websocket.interfaces.WebSocketSendMessage;
import com.mymarkdown.app.websocket.message.MessagePojo;
import javafx.scene.web.WebEngine;
import javafx.stage.FileChooser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.BlockingQueue;

/**
 * @author zenglun
 * @date 2021/12/5 10:00 上午
 * @description: 打开操作的处理
 */
@Slf4j
@KeyWord(FxEventEnum.OPEN_MD_FILE)
@Component("openFileMenuHandlerImpl")
public class OpenFileMenuHandlerImpl implements MenuHandler, KeyWordHandler {

    @Autowired
    private WebSocketSendMessage webSocketSendMessage;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private FileWatch fileWatch;

    @Autowired
    private ModifyWindow modifyWindow;

    @Override
    public void handler(WebEngine engine, FxEvent event) {
        //打开文件
        Object source = event.getSource();
        Object target = event.getTarget();
        File file = null;
        MessagePojo messagePojo = new MessagePojo();
        if (Objects.isNull(source)) {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("保存文件");
            FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("markdown", "*.md");
            fileChooser.getExtensionFilters().add(extFilter);
            file = fileChooser.showOpenDialog(FxApplication.getPrimaryStage());
            messagePojo.setMessageType(MessageTypeEnum.TISP_MSG.getMessageType());
            if (Objects.isNull(file)) {
                // 文件为空!
                messagePojo.setBody("当前目标操作文件未找到");
                webSocketSendMessage.sendMessage(messagePojo);
                return;
            }
            openMd(file);
        } else if (source instanceof File && target instanceof FxTreeItem) {
            file = (File) source;
            if (file.isFile()) {
                openMd(file);
            }
            if (file.isDirectory()) {
                openDirectory(file, (FxTreeItem)target);
            }
        }
    }

    private void openDirectory(File file, FxTreeItem fxTreeItem) {
        //给当前的item添加相关子节点了
        CurrentUserUtil.getSelf().getAllCurrentFileBuildTree(fxTreeItem, file);
        fileWatch.addWatchPath(file.getPath());
    }

    private void openMd(File file) {
        MessagePojo messagePojo = new MessagePojo();
        //如果文件不等于null,则读取文件信息
        FileInputStream fileInputStream = null;
        try {
            BlockingQueue<File> operationFile = userInfoService.getOperationFile();
            File peek = operationFile.peek();
            if (!Objects.isNull(peek)) {
                operationFile.take();
            }
            operationFile.put(file);

            //将当前文件内容存入
            messagePojo.setMessageType(MessageTypeEnum.LOAD_FILE.getMessageType());
            webSocketSendMessage.sendMessage(messagePojo);
            //设置当前操作的文件夹和最近操作的文件
            List<String> historyOperationFile = this.userInfoService.getUserLatelyInfo().getHistoryOperationFile();
            if (!CollectionUtil.contains(historyOperationFile, file.getPath())){
                modifyWindow.addHistoryOperationTreeItem(file.getPath());
            }
            userInfoService.getUserLatelyInfo().setLatelyOperationFile(file.getPath()).addHistoryOperation(file.getPath());
        } catch (InterruptedException e) {
            log.error("[OpenFileMenuHandlerImpl]---[handler],设置当前操作文件被终端,异常信息为:{}", e);
        } finally {
            Optional.ofNullable(fileInputStream).ifPresent(e -> {
                try {
                    e.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                    log.error("[OpenFileMenuHandlerImpl]---[handler],关闭流出现错误,异常信息为:{}", ioException);
                }
            });
        }
    }

    @Override
    public boolean afterHandler(WebEngine engine, FxEvent event) {
        return true;
    }

    @Override
    public void beforeHandler(WebEngine engine, FxEvent event) {

    }

}
